package com.ctyon.watchmanager.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.launcher.ARouter;
import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.TSnackbarUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.bean.ContactBean;
import com.ctyon.watchmanager.databinding.FragmentContactsBinding;
import com.ctyon.watchmanager.listener.ItemClickListener;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.present.ContactsPresenter;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.ctyon.watchmanager.ui.adapter.ContactsAdapter;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.ctyon.common.container.ARouterPath.ROUTER_ACTIVITY_CONTAINER;
import static com.ctyon.watchmanager.ui.activity.ContainerActivity.PARAM1;
import static com.ctyon.watchmanager.ui.activity.ContainerActivity.PARAM2;
import static com.ctyon.watchmanager.ui.activity.ContainerActivity.TAB_INDEX_PARAM;

/**
 * CreateDate：19-6-25 on 上午9:14
 * Describe:
 * Coder: lee
 */
public class ContactsFragment extends BaseFragment {

    public static final String TAG = "ContactsFragment";

    private FragmentContactsBinding mBinding;
    private ContactsAdapter mAdapter;

    private AlertDialog.Builder builder;
    private int mIndex;

    private List<ContactBean> contactList = new ArrayList<>();

    public static ContactsFragment newInstance() {
        final ContactsFragment fragment = new ContactsFragment();
        final Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_contacts, container, false);
        mBinding.setContactsPresenter(contactsPresenter);

        mAdapter = new ContactsAdapter(itemClickListener);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        mBinding.contactsRecycle.setLayoutManager(layoutManager);
        mBinding.contactsRecycle.setAdapter(mAdapter);

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        String contactsStr = BasicApp.getInstance().getWatch().getContacts();
        contactList.clear();
        if (!DataUtil.isEmptyAnd(contactsStr) && contactsStr.contains("&")) {
            String[] strings = contactsStr.split("&");
            ContactBean contactBean = null;
            for (int i = 0; i < strings.length; i++) {
                if (i%2 == 0){
                    contactBean = new ContactBean();
                    contactBean.setNumber(strings[i]);
                } else {
                    contactBean.setName(DataUtil.unicode2String(strings[i]));
                    contactList.add(contactBean);
                }
            }
            loadContacts();
        } else {
            mBinding.setIsEmpty(true);
        }
    }

    private final ContactsPresenter contactsPresenter = new ContactsPresenter() {
        @Override
        public void onImportClick() {
            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
                    .withString(TAB_INDEX_PARAM, ContactsImportFragment.TAG)
                    .navigation();
        }

        @Override
        public void onAddClick() {
            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
                    .withString(TAB_INDEX_PARAM, ContactsAddFragment.TAG)
                    .navigation();
        }
    };

    private final ItemClickListener<Integer> itemClickListener = new ItemClickListener<Integer>() {
        @Override
        public void onItemClick(Integer index) {
            Logger.d("id = " + index);
            ContactBean contact = contactList.get(index);
            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
                    .withString(TAB_INDEX_PARAM, ContactsAddFragment.TAG)
                    .withString(PARAM1, contact.getName())
                    .withString(PARAM2, contact.getNumber())
                    .navigation();
        }

        @Override
        public void onBt1Click(Integer index) {
            Logger.d("onBt1Click : " + index);
            mIndex = index;
            showDialog();
        }

    };

    private void loadContacts() {
        if (contactList.size() > 0) {
            mBinding.setIsEmpty(false);
        } else {
            mBinding.setIsEmpty(true);
        }
        mAdapter.setData(contactList);
    }

    private void uploadContacts(int index) {
        final StringBuilder contactsData = new StringBuilder();
        Logger.t(LTAG).d("contactList size = " + contactList.size());
        List<ContactBean> list = new ArrayList<>();
        list.addAll(contactList);
        list.remove(index);
        for (int i = 0; i < list.size(); i++) {
            if (i > 0) {
                contactsData.append("&");
            }
            contactsData.append(list.get(i).toString());
        }
        String data = contactsData.toString().replace(" ", "");
        Logger.t(LTAG).d("contactsData : " + data);
        final String method = "contacts";
        if (NetService.getInstance().isDisable(method)) {
            TSnackbarUtil.TSBError(getActivity(), "请稍候...");
            return;
        }
        NetService.getInstance()
                .method(method)
                .contacts(BasicApp.getInstance().getManager().getManagerId(), BasicApp.getInstance().getWatch().getMeid(), data)
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponseEntity>() {
                    @Override
                    public void onSuccess(BaseResponseEntity responseEntity) {
                        Logger.d("onSuccess : " + responseEntity.toString());
                        TSnackbarUtil.TSBSuccess(getActivity(), "操作成功");
                        BasicApp.getInstance().getWatch().setContacts(data);
                        mAdapter.remove(index);
                        contactList.remove(index);
                        if (contactList.size() > 0) {
                            mBinding.setIsEmpty(false);
                        } else {
                            mBinding.setIsEmpty(true);
                        }
                    }

                    @Override
                    public String onOver() {
                        return method;
                    }
                });
    }

    private void showDialog() {
        if (null == builder) {
            builder = new AlertDialog.Builder(getActivity(), R.style.MyDialog);
            builder.setTitle("删除联系人")
                    .setMessage("确定删除吗?")
                    .setPositiveButton("确定", (dialog, which) -> {
                        uploadContacts(mIndex);
                    });
        }
        builder.show();
    }
}
